package com.eleventwelve.iris.web.controller;

import imageUtil.*;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.opentides.service.FileInfoService;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.eleventwelve.iris.utilities.ImageUtil;
import com.eleventwelve.iris.entity.PhotoUploadable;

@SuppressWarnings("deprecation")
public class AdjustImageController extends SimpleFormController {
	
private FileInfoService fileInfoService;

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}
	
	protected void processAdjust(PhotoUploadable uploadable, int x, int y, int x2, int y2) throws IOException {

		String filePath = uploadable.getFiles().get(uploadable.getFiles().size()-1).getFullPath();
		
		Image originalImage, large, thumb, mini;
		
		originalImage = ImageLoader.fromFile(filePath);
		
		if(originalImage.getWidth() > 600) {
			originalImage = originalImage.getResizedToWidth(600);
		}
		
		large = originalImage.crop(x, y, x2, y2);

		large.writeToFile(new File(ImageUtil.buildFileName(filePath, "_large") + ".png"));
		thumb = large.getResizedToSquare(100, 0.0);
		mini = large.getResizedToSquare(50, 0.0);
			
		thumb.writeToFile(new File(ImageUtil.buildFileName(filePath, "_thumb") + ".png"));
		mini.writeToFile(new File(ImageUtil.buildFileName(filePath, "_mini") + ".png"));
		
	}

	public void setFileInfoService(FileInfoService fileInfoService) {
		this.fileInfoService = fileInfoService;
	}
	
	public FileInfoService getFileInfoService() {
		return fileInfoService;
	}

}
